// @/util/eventbus/notificationEventBus.js
import { ref } from 'vue'

// 创建事件总线
class NotificationEventBus {
    constructor() {
        this.events = new Map()

        // 响应式通知状态
        this.notifications = ref([])
        this.unreadCount = ref(0)

        // 音频管理
        this.audioContext = null
        this.isAudioEnabled = ref(true)
    }

    // 注册事件监听器
    on(event, callback) {
        if (!this.events.has(event)) {
            this.events.set(event, [])
        }
        this.events.get(event).push(callback)
    }

    // 移除事件监听器
    off(event, callback) {
        if (!this.events.has(event)) return

        const callbacks = this.events.get(event)
        const index = callbacks.indexOf(callback)
        if (index > -1) {
            callbacks.splice(index, 1)
        }
    }

    // 发送事件
    emit(event, data) {
        if (!this.events.has(event)) return

        this.events.get(event).forEach(callback => {
            try {
                callback(data)
            } catch (error) {
                console.error(`[NotificationEventBus] 事件回调执行失败:`, error)
            }
        })
    }

    // 播放通知提示音
    async playNotificationSound(type = 'success') {
        if (!this.isAudioEnabled.value) return

        try {
            // 使用Web Audio API生成提示音
            if (!this.audioContext) {
                this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
            }

            const oscillator = this.audioContext.createOscillator()
            const gainNode = this.audioContext.createGain()

            // 根据通知类型设置不同的音调
            const frequencies = {
                success: [800, 1000, 1200], // 成功：上升音调
                error: [400, 300, 200],     // 错误：下降音调
                info: [600, 600, 600]       // 信息：平稳音调
            }

            const freqPattern = frequencies[type] || frequencies.info

            // 连接音频节点
            oscillator.connect(gainNode)
            gainNode.connect(this.audioContext.destination)

            // 设置音量包络
            const now = this.audioContext.currentTime
            gainNode.gain.setValueAtTime(0, now)
            gainNode.gain.linearRampToValueAtTime(0.1, now + 0.01)
            gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.3)

            // 播放音调序列
            let time = now
            freqPattern.forEach((freq, index) => {
                if (index > 0) {
                    const newOscillator = this.audioContext.createOscillator()
                    const newGainNode = this.audioContext.createGain()

                    newOscillator.connect(newGainNode)
                    newGainNode.connect(this.audioContext.destination)

                    newOscillator.frequency.setValueAtTime(freq, time)
                    newOscillator.type = 'sine'

                    newGainNode.gain.setValueAtTime(0, time)
                    newGainNode.gain.linearRampToValueAtTime(0.1, time + 0.01)
                    newGainNode.gain.exponentialRampToValueAtTime(0.01, time + 0.15)

                    newOscillator.start(time)
                    newOscillator.stop(time + 0.15)

                    time += 0.1
                } else {
                    oscillator.frequency.setValueAtTime(freq, time)
                    oscillator.type = 'sine'
                    oscillator.start(time)
                    oscillator.stop(time + 0.15)
                    time += 0.1
                }
            })

        } catch (error) {
            console.warn('[NotificationEventBus] 播放提示音失败:', error)
            // 降级到系统提示音
            this.playFallbackSound()
        }
    }

    // 降级提示音（使用HTML5 Audio）
    playFallbackSound() {
        try {
            // 创建简单的提示音
            const audio = new Audio()
            audio.volume = 0.3

            // 使用data URL创建简单的提示音
            const audioData = 'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmweETGH0vLZeTEGVa3P7td9PAUKWK7b76NQEAo8ltryxW8gAjFw1PH0yzUHV4LQqhgGCCtOhAg='
            audio.src = audioData
            audio.play().catch(() => {
                // 如果播放失败，静默处理
            })
        } catch (error) {
            console.warn('[NotificationEventBus] 降级提示音播放失败:', error)
        }
    }

    // 设置音频开关
    setAudioEnabled(enabled) {
        this.isAudioEnabled.value = enabled
        localStorage.setItem('notification-audio-enabled', enabled.toString())
    }

    // 获取音频开关状态
    getAudioEnabled() {
        const saved = localStorage.getItem('notification-audio-enabled')
        if (saved !== null) {
            this.isAudioEnabled.value = saved === 'true'
        }
        return this.isAudioEnabled.value
    }

    // 发送评估完成通知
    emitEvaluationCompleted(payload) {
        console.log('[NotificationEventBus] 发送评估完成事件:', payload)

        // 播放成功提示音
        this.playNotificationSound('success')

        // 发送事件
        this.emit('evaluation_completed', {
            type: 'evaluation_completed',
            payload,
            timestamp: new Date().toISOString()
        })
    }

    // 发送评估失败通知
    emitEvaluationFailed(payload) {
        console.log('[NotificationEventBus] 发送评估失败事件:', payload)

        // 播放错误提示音
        this.playNotificationSound('error')

        // 发送事件
        this.emit('evaluation_failed', {
            type: 'evaluation_failed',
            payload,
            timestamp: new Date().toISOString()
        })
    }

    // 发送通用通知
    emitNotification(type, payload) {
        console.log('[NotificationEventBus] 发送通知事件:', type, payload)

        // 播放对应类型提示音
        this.playNotificationSound(type === 'evaluation_completed' ? 'success' :
            type === 'evaluation_failed' ? 'error' : 'info')

        // 发送事件
        this.emit('notification', {
            type,
            payload,
            timestamp: new Date().toISOString()
        })
    }

    // 清理资源
    destroy() {
        this.events.clear()
        if (this.audioContext && this.audioContext.state !== 'closed') {
            this.audioContext.close()
        }
    }
}

// 创建全局实例
const notificationEventBus = new NotificationEventBus()

// 初始化音频设置
notificationEventBus.getAudioEnabled()

export default notificationEventBus